/**
 * 
 */
package com.dhcc.cdbp.query;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * 短语查询：
 * 	查询文档中包含指定的一个Term或多个Term,多个Term之间可以限制间隔（slop参数）
 * @author 谢进军
 *
 */
public class PhraseQueryTest {
	private Directory directory = null;
	@Before public void setUp() throws Exception {
		directory = new RAMDirectory();  
	    Analyzer analyzer = new StandardAnalyzer();  
	    IndexWriterConfig iwc = new IndexWriterConfig(analyzer);  
	    iwc.setOpenMode(OpenMode.CREATE);  
	    IndexWriter writer = new IndexWriter(directory, iwc);  
	  
	    Document doc = new Document();  
	    doc.add(new TextField("text", "quick brown fox", Field.Store.YES));  
	    writer.addDocument(doc);  
	          
	    doc = new Document();  
	    doc.add(new TextField("text", "jumps over lazy broun dog", Field.Store.YES));  
	    writer.addDocument(doc);  
	          
	    doc = new Document();  
	    doc.add(new TextField("text", "jumps over extremely very lazy broxn dog", Field.Store.YES));  
	    writer.addDocument(doc);  
	          
	    writer.close();  
	}
	@Test public void test() throws IOException {
		 IndexReader reader = DirectoryReader.open(directory);  
	     IndexSearcher searcher = new IndexSearcher(reader);  
	          
	     String term1 = "dog";  
	     String term2 = "jumps";  
	     PhraseQuery phraseQuery = new PhraseQuery();  
	     phraseQuery.add(new Term("text",term1));  
	     phraseQuery.add(new Term("text",term2));  
//	     phraseQuery.setSlop(15);  
	     phraseQuery.setSlop(6);  
	          
	     TopDocs results = searcher.search(phraseQuery, 100);  
	     ScoreDoc[] scoreDocs = results.scoreDocs;  
	          
	     for (int i = 0; i < scoreDocs.length; ++i) {  
	         //System.out.println(searcher.explain(query, scoreDocs[i].doc));  
	         int docID = scoreDocs[i].doc;  
	         Document document = searcher.doc(docID);  
	         String path = document.get("text");  
	         System.out.println("text:" + path);  
	     }  
	}
	@After public void tearDown() throws Exception {
		directory.close();
	}
}
